package com.ccrego.haiyi.wxapi;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.ccrego.haiyi.account.Account;
import com.ccrego.haiyi.account.AccountManager;
import com.ccrego.haiyi.account.login.WxBindActivity;
import com.ccrego.haiyi.account.UrlCenter;
import com.ccrego.haiyi.app.MainActivity;
import com.ccrego.haiyi.common.http.MyHttpRequest;
import com.ccrego.haiyi.common.http.TokenInfo;
import com.ccrego.haiyi.utils.WechatHelper;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.umeng.socialize.weixin.view.WXCallbackActivity;

import org.json.JSONException;
import org.json.JSONObject;

import static com.ccrego.haiyi.utils.WechatHelper.WECHAT_APP_ID;
import static com.ccrego.haiyi.utils.WechatHelper.WECHAT_SECRET;

/**
 * 微信的分享回调页面
 *
 * 只要AndroidManifest等配置正确，友盟就可以正确回调微信的分享结果，不需要我们再处理
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2016-07-11
 * @Version: 1.0.0
 */

public class WXEntryActivity extends WXCallbackActivity implements IWXAPIEventHandler {
    private static String TAG = "WXEntryActivity";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IWXAPI iwxapi = WechatHelper.getInstance().init(this);
        iwxapi.handleIntent(getIntent(), this);
    }


    @Override
    public void onResp(BaseResp resp) {
        super.onResp(resp);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        Log.e(TAG, "onReq");
    }

    @Override
    public void onResp(com.tencent.mm.opensdk.modelbase.BaseResp baseResp) {
        Log.e(TAG, "onResp"+baseResp.errCode);
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                String code = ((SendAuth.Resp) baseResp).code;
                if (TextUtils.isEmpty(code)) {
                    EasyToast.showToast(WXEntryActivity.this, "抱歉~微信授权失败", Toast.LENGTH_SHORT);
                    return;
                }
                getOpenID(code);
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                    finish();
                break;
        }

    }

    //通过code获取openid
    private void getOpenID(String code) {
        // APP_ID和APP_Secret在微信开发平台添加应用的时候会生成，grant_type 用默认的"authorization_code"即可.
        String urlStr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WECHAT_APP_ID+"&secret="+WECHAT_SECRET+
                "&code="+code+"&grant_type=authorization_code";
        IHttpRequest request = new MyHttpRequest(getBaseContext());
        request.get(urlStr, null, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);

                try {
                    JSONObject joj = new JSONObject(o);
                    //服务端通过openid 判断是否绑定了
                    ifBindPhone(joj.getString("openid"),joj.getString("access_token"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    //服务端通过openid 判断是否绑定了
    private void ifBindPhone(final String openId,final String token) {
        IHttpRequest request = new HttpRequest(getBaseContext());
        UrlParams params = new UrlParams();
        params.put("open_id",openId);
        request.get(UrlCenter.WX_LOGIN, params, new DataRequestListener<TokenInfo>(TokenInfo.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(TokenInfo o) {
                super.onSuccess(o);
                Log.e("ooooo", "25525");
                //尝试对空字符串进行操作，并捕获异常，输出异常
                if (TextUtils.isEmpty(o.getAccessToken())) {
                    //未绑定手机号 要获得微信的信息
                    Log.e("ooooo", "未绑定");
                    getUserMesg(openId, token);
                } else {
                    Log.e("ooooo", o.toString());
                    AccountManager.updateTokenInfo(o);
                    setAccount(o);
                }
            }
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }
    /**
     * 获取微信的个人信息
     *
     * @param access_token
     * @param openid
     */
    private void getUserMesg(final String openid,final String access_token) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        Log.e("ooooooo",path);
        IHttpRequest request = new HttpRequest(getBaseContext());
        request.get(path, null, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                Log.e("ooooooo",o);
                WxBindActivity.start(WXEntryActivity.this,o);
                finish();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });

    }

    private void setAccount(final TokenInfo o) {
        IHttpRequest request = new MyHttpRequest(getBaseContext());
        String requestUrl = String.format(UrlCenter.USER);
        request.get(requestUrl, null, new DataRequestListener<Account>(Account.class) {
            @Override
            public void onSuccess(Account account) {
                AccountManager.setCurrentAccount(account);
                EasyToast.showToast(getBaseContext(), "登录成功");
                MainActivity.start(WXEntryActivity.this);
                finish();
            }

            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                EasyToast.showToast(WXEntryActivity.this, strMsg);
            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
           finish();
        }
        return false;
    }

}
